package com.ming.sevice.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ming.domain.Sku;
import com.ming.feign.CartSkuFeign;
import com.ming.vo.CartMoney;
import com.ming.vo.ShopCartItem;
import com.ming.vo.ShopCartResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ming.domain.Basket;
import com.ming.mapper.BasketMapper;
import com.ming.sevice.BasketService;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Author:何元才
 * @Desc:
 * @data:2021-04-08 19:19
 */
@Service
@Slf4j
public class BasketServiceImpl extends ServiceImpl<BasketMapper, Basket> implements BasketService {


    @Autowired
    private BasketMapper basketMapper;

    @Autowired
    private CartSkuFeign cartSkuFeign;

    /**
     * 查询用户购物车总条数
     *
     * @param userId
     * @return
     */
    @Override
    public Integer getBasketCountByUserId(String userId) {
//        List<Basket> baskets = basketMapper.selectList(new LambdaQueryWrapper<Basket>()
//                .eq(Basket::getUserId, userId)
//        );
//        Integer count = baskets.stream()
//                .map(Basket::getBasketCount)
//                .reduce(Integer::sum)
//                .get();
//        return count;

        List<Object> objs = basketMapper.selectObjs(new QueryWrapper<Basket>()
                .select(" ifnull(sum(basket_count),0) ")
                .eq("user_id", userId)
        );
        if (!CollectionUtils.isEmpty(objs) && objs.get(0) != null ){
            return Integer.parseInt(objs.get(0).toString());
        }
        return 0;
    }

    /**
     * 查询购物车详情
     *
     * @param userId
     * @return
     */
    @Override
    public List<ShopCartResult> getCartInfo(String userId) {
        //需要查询购物车表 拿到list集合
        List<Basket> baskets = basketMapper.selectList(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, userId)
                .orderByDesc(Basket::getBasketDate)
        );
        if (CollectionUtils.isEmpty(baskets)){
            return Collections.emptyList();
        }
        //2.1拿到skuIds
        List<Long> skuIds = baskets.stream()
                .map(Basket::getSkuId)
                .collect(Collectors.toList());
        //2.远程调用商品 更具skuIds拿到 sku集合
        List<Sku> skuList = cartSkuFeign.getSkuListByIds(skuIds);
        if (CollectionUtils.isEmpty(skuList)) {
            System.out.println("----");
            throw  new RuntimeException("服务器正在维护中");
        }
        //创建购物车返回对象集合
        ArrayList<ShopCartResult> shopCartResults = new ArrayList<>();
        //创建购物车返回对象
        ShopCartResult shopCartResult = new ShopCartResult();
        //设置一些金额运费 满减等
        shopCartResult.setDisCount(BigDecimal.ZERO);
        shopCartResult.setTransfee(BigDecimal.ZERO);
        //创建购物车中商品条目集合
        List<ShopCartItem> shopCartItems = new ArrayList<>();

        //循环 basket 组装数据返回
        baskets.forEach(basket -> {
            //创建一个商品信息对象
            ShopCartItem shopCartItem = new ShopCartItem();
            //循环skuList 拿到对应一个sku
            Sku sku1 = skuList.stream()
                    .filter(sku -> sku.getSkuId().equals(basket.getSkuId()))
                    .collect(Collectors.toList())
                    .get(0);
            //填充属性 商品信息
            BeanUtil.copyProperties(sku1,shopCartItem,true);
            //数量 checked
            shopCartItem.setBasketCount(basket.getBasketCount());
            shopCartItem.setBasketId(basket.getBasketId());
            shopCartItem.setChecked(true);
            // 设置商品信息对象放到  商品条目集合 中
            shopCartItems.add(shopCartItem);
        });
        // 设置 商品条目集合 放到 购物车返回对象中
        shopCartResult.setShopCartItems(shopCartItems);
        //设置 购物车返回对象到 购物车返回集合中
        shopCartResults.add(shopCartResult);
        //返回
        return shopCartResults;
    }

    /**
     * 商品里面修改 可能是增加 也可能是修改
     * skuid
     * prodid
     * count
     *
     * @param basket
     * @return
     */
    @Override
    public void changeItem(Basket basket) {
        log.info("修改购物车信息{}", JSON.toJSONString(basket));
        //1.先更具用户id和skuId唯一确定一行数据
        //2.如果能查到 就是修改
        //3.如果没有就是新增
        Basket oldBasket = basketMapper.selectOne(new LambdaQueryWrapper<Basket>()
                .eq(Basket::getUserId, basket.getUserId())
                .eq(Basket::getSkuId, basket.getSkuId())
        );
        if (ObjectUtils.isEmpty(oldBasket)){
            //新增
            Integer count = getBasketCountByUserId(basket.getUserId());
            int finalCount = count + basket.getBasketCount();
            if (finalCount >= 100){
                int i = 100 - count;
                //不能新增
                throw new IllegalArgumentException("购物车商品数量达到上限,还可以添加" + i + "个");
            }
            basket.setBasketDate(new Date());
            basketMapper.insert(basket);
            return;
        }
        //如果不是新增 可能是修改
        Integer oldCount = oldBasket.getBasketCount();
        //新的值 + - 号判断
        int newCount = oldCount + basket.getBasketCount();
        if (newCount == 0){
            //删除
            basketMapper.deleteById(oldBasket.getBasketId());
            return;
        }
        if (newCount < 0){
            //报错
            throw new IllegalArgumentException("购物车商品数量不能为负数");
        }
        //修改
        oldBasket.setBasketCount(newCount);
        oldBasket.setBasketDate(new Date());
        basketMapper.updateById(oldBasket);
    }

    /**
     * 计算购物车选中的商品总金额
     *
     * @param basketIds
     * @return
     */
    @Override
    public CartMoney calcCartMoney(List<Long> basketIds) {
        CartMoney cartMoney = new CartMoney();
        if (CollectionUtils.isEmpty(basketIds)){
            return cartMoney;
        }
        //查询购物车集合 拿到sku 拿到数量
        List<Basket> baskets = basketMapper.selectBatchIds(basketIds);
        //断言不为空  为空报错
        assert baskets != null;
        List<Long> skuIds = baskets.stream()
                .map(Basket::getSkuId)
                .collect(Collectors.toList());
        //远程调用拿到sku的集合
        List<Sku> skuList = cartSkuFeign.getSkuListByIds(skuIds);
        if (CollectionUtils.isEmpty(skuList)) {
            throw new RuntimeException("服务器维护中，请稍后再试");
        }
        //创建一个保存单个商品总价的集合
        List<BigDecimal> totalMoneyList = new ArrayList<>();
        //计算
        baskets.forEach(basket -> {
            Integer basketCount = basket.getBasketCount();
            //拿到具体的sku
            Sku sku1 = skuList.stream()
                    .filter(sku -> sku.getSkuId().equals(basket.getSkuId()))
                    .collect(Collectors.toList())
                    .get(0);
            BigDecimal price = sku1.getPrice();
            //计算一下
            BigDecimal oneMoney = price.multiply(new BigDecimal(basketCount));
            totalMoneyList.add(oneMoney);
        });
        // 999 , 1080  2100  for each  stream  只要对集合的操作 直接就用stream
        BigDecimal totalMoney = totalMoneyList.stream()
                .reduce(BigDecimal::add)
                .get();
        cartMoney.setTotalMoney(totalMoney);
        //减满金额
        cartMoney.setFinalMoney(totalMoney);
        //查询当前用户是否优惠券是否可以用 从而设定满减金额
        return cartMoney;
    }


}
